package com.eqdd.yiqidian.ui.companyspace

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.DemandMatchBean
import com.eqdd.yiqidian.bean.ProductDemandBean
import com.eqdd.yiqidian.bean.rebuild.OptionBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.*
import com.eqdd.yiqidian.kotlin.deleteDialog
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.kotlin.inflater
import com.eqdd.yiqidian.ui.IndustryTypeListActivity
import com.eqdd.yiqidian.ui.base.EditTextActivity
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCSwipeRefreshHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.activity_demand_info.*
import kotlinx.android.synthetic.main.list_item_171.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.util.*

/**
 *
 * Created by jhj on 18-7-25.
 */
class ProDemandInfoActivity : BaseActivity() {


    private var id: Int = -1
    private var type: Int = -1
    private var function: Int = -1
    private var demandBean: ProductDemandBean? = null
    private var mSlimAdapterEx: SlimAdapterEx<ProductDemandBean.IndexListBean>? = null
    private var nSlimAdapterEx: SlimAdapterEx<DemandMatchBean>? = null
    private var view: View? = null

    private var indexDeleteUrl = ""
    private var updateUrl = ""


    override fun initBinding() {
        setContentView(R.layout.activity_demand_info)
        type = intent.getIntExtra(Config.TYPE, -1)
        id = intent.getIntExtra(Config.ID, -1)
        function = intent.getIntExtra("fun", -1)


        val title = if (type == 0) {
            "供方信息详情"
        } else if (type == 1) {
            "买方信息详情"
        } else if (type == 2) {
            "需求详情"
        } else {
            "信息详情"
        }
        if (id == -1 || type == -1 || function == -1) {
            toast("获取详情失败")
            finish()
            return
        }

        if (type == 0) {
            indexDeleteUrl = HttpConfig.BASE_URL + HttpConfig.SUPPLY_INDEX_DELETE
            updateUrl = HttpConfig.BASE_URL + HttpConfig.SUPPLY_UPDATE
        } else if (type == 1) {
            indexDeleteUrl = HttpConfig.BASE_URL + HttpConfig.BUYER_INDEX_DELETE
            updateUrl = HttpConfig.BASE_URL + HttpConfig.BUYER_UPDATE
        }

        initTopTitleBar(View.VISIBLE, title)
    }


    override fun initData() {
        OkGo.post<HttpResult<ProductDemandBean>>(HttpConfig.BASE_URL + HttpConfig.DEMAND_DETAIL)
                .params("demandId", id)
                .execute(object : DialogCallBack<HttpResult<ProductDemandBean>>(this) {
                    override fun onSuccess(response: Response<HttpResult<ProductDemandBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            demandBean = result.items
                            setView()
                        } else {
                            toast("获取详情失败")
                        }
                    }
                })
        match()

    }


    override fun setView() {
        demandBean?.let {
            val density = resources.displayMetrics.density
            view = inflater.inflate(R.layout.list_item_171, null)
            view?.let { view ->
                view.tv_name.text = it.productName
                view.tv_code.text = it.guoBiaoCode
                view.tv_type.text = it.productType
                view.tv_description.text = it.productDesc
                if (function == 0) {
                    view.tv_add.visibility = View.VISIBLE
                    view.layout_name.onClick {
                        startActivityForResult<EditTextActivity>(0, "title" to "产品名称", "tip" to "产品名称", "content" to view.tv_name.text.toString())
                    }
                    view.layout_code.onClick {
                        startActivityForResult<EditTextActivity>(1, "title" to "国标代码", "tip" to "国标代码", "content" to view.tv_code.text.toString())
                    }
                    view.layout_type.onClick {
                        startActivityForResult<IndustryTypeListActivity>(2, Config.TYPE to 2, Config.TITLE to "产品类型")
                    }
                    view.layout_description.onClick {
                        startActivityForResult<EditTextActivity>(3, "title" to "产品描述", "tip" to "产品描述", "content" to view.tv_description.text.toString())
                    }
                    view.tv_add.onClick {
                        startActivityForResult<ProductIndexAddActivity>(Config.ADD, Config.ID to id)
                    }
                } else {
                    view.tv_add.visibility = View.GONE
                }

                view.recyclerView.layoutManager = LinearLayoutManager(this)
                view.recyclerView.addItemDecoration(DividerLineItemDecoration(this).setFirstDraw(true).setLeftPadding((density * 25).toInt()).setRightPadding((density * 25).toInt()))
                mSlimAdapterEx = SlimAdapterEx.create()
                        .register<ProductDemandBean.IndexListBean>(R.layout.list_item_169, SlimInjector<ProductDemandBean.IndexListBean> { data, injector ->
                            injector?.text(R.id.tv_index, data?.indexTypeKey)
                                    ?.text(R.id.tv_index_value, data?.indexTypeValue)
                                    ?.visibility(R.id.layout_image, if (data?.indexImage.isNullOrBlank()) View.GONE else View.VISIBLE)
                                    ?.image(R.id.iv_image, data?.indexImage)
                                    ?.clicked(R.id.iv_image) {
                                        data?.indexImage?.let { it1 -> imgPathPreview(it1) }
                                    }
                        })
                        ?.attachTo(view.recyclerView)
                        ?.updateData(demandBean?.indexList as List<ProductDemandBean.IndexListBean>?
                                ?: listOf<ProductDemandBean.IndexListBean>()) as SlimAdapterEx<ProductDemandBean.IndexListBean>?

                if (function == 0) {
                    ItemClickSupport.addTo(view.recyclerView)
                            .setOnItemLongClickListener { recyclerView, position, v ->
                                deleteDialog(indexDeleteUrl, "是否删除“${demandBean?.indexList?.get(position)?.indexTypeKey
                                        ?: "该数据"}？”", "buyerIndexId" to demandBean?.indexList?.get(position)?.id, isFinish = false) {
                                    mSlimAdapterEx?.data?.removeAt(position)
                                    mSlimAdapterEx?.notifyItemRemoved(position)
                                }
                                true
                            }
                }

                nSlimAdapterEx?.addHeader(view)
            }
        }
    }


    private fun match() {
        val list = arrayListOf<DemandMatchBean>()
        var pageNum = 0
        MVCSwipeRefreshHelper.setLoadViewFractory(CustomLoadViewFactory().setShowEmpty(false))
        swipeRefreshLayout.setProgressViewEndTarget(true, 0)
        val mvcHelper = MVCSwipeRefreshHelper<List<DemandMatchBean>>(swipeRefreshLayout)
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerView.addItemDecoration(DividerLineItemDecoration(this))
        nSlimAdapterEx = SlimAdapterEx.create().register<DemandMatchBean>(R.layout.list_item_170, SlimInjector<DemandMatchBean> { data, injector ->
            injector?.text(R.id.tv_name, data?.productName)
                    ?.text(R.id.tv_price, String.format(Locale.CHINA, "￥%d元", data?.productPrice
                            ?: 0))
                    ?.image(R.id.imageView, data?.image)
        }).attachTo(mRecyclerView).updateData(list as List<DemandMatchBean>?) as SlimAdapterEx<DemandMatchBean>?

        val dataSource = ModelRx2DataSource<DemandMatchBean>(ModelRx2DataSource.OnLoadSource<DemandMatchBean> { page, _ ->
            pageNum = if (page == 1) 0 else pageNum
            OkGo.post<HttpResult<List<DemandMatchBean>>>(HttpConfig.BASE_URL + HttpConfig.DEMAND_MATCH)
                    .params("demandId", id)
                    .params("page", pageNum)
                    .params("count", 10)
                    .converter(object : JsonConverter<HttpResult<List<DemandMatchBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    }).adapt(FlowableBody<HttpResult<List<DemandMatchBean>>>())
                    .flatMap({ result ->
                        if (page == 1) {
                            mvcHelper.isAutoLoadMore = true
                        }
                        pageNum = result.page

                        val dataList = result.items ?: arrayListOf<DemandMatchBean>()
                        Flowable.just<MutableList<DemandMatchBean>>(dataList.toMutableList())
                    })

        }, 10)

        mvcHelper.setDataSource(dataSource)
        mvcHelper.adapter = nSlimAdapterEx
        mvcHelper.refresh()
    }

    fun update(str: String) {
        OkGo.post<HttpResult<*>>(updateUrl)
                .params("userGuid", user.guid)
                .params("companyId", user.companyId)
                .params("buyerId", id)
                .params("para", str)
                .execute(object : DialogCallBack<HttpResult<*>>(this) {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            toast("修改成功")
                        } else {
                            toast("修改失败")
                        }
                    }
                })
    }

    override fun onDestroy() {
        super.onDestroy()
        MVCSwipeRefreshHelper.setLoadViewFractory(CustomLoadViewFactory().setShowEmpty(true))
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Config.INTENT_CONTENT) {
            val content = data?.getStringExtra("content")
            val str: String
            str = when (requestCode) {
                0 -> {
                    view?.tv_name?.text = content
                    "productName='$content'"
                }
                1 -> {
                    view?.tv_code?.text = content
                    "GuoBiaoCode='$content'"
                }
                3 -> {
                    view?.tv_description?.text = content
                    "productDesc='$content'"
                }
                else -> ""
            }
            update(str)
        }
        if (resultCode == Activity.RESULT_OK && requestCode == Config.ADD) {
            val bean = data?.getSerializableExtra("data") as ProductDemandBean.IndexListBean
            val indexBean = ProductDemandBean.IndexListBean()
            indexBean.indexImage = bean.indexImage
            indexBean.indexTypeKey = bean.indexTypeKey
            indexBean.indexTypeValue = bean.indexTypeValue
            mSlimAdapterEx?.data?.add(indexBean)
            mSlimAdapterEx?.notifyDataSetChanged()
        }
        if (resultCode == Activity.RESULT_OK && requestCode == 2) {
            val optionBean = data?.getSerializableExtra("data") as? OptionBean
            view?.tv_type?.text = optionBean?.name
            optionBean?.let { update("productType='${it.name}'") }
        }

    }


}